colorAdminApp.controller('resourcesManageController', function($scope,$compile,$rootScope,$http,$state,$stateParams,modalService) {
	
	if($stateParams.type.toUpperCase()=="FUNCTION"){
		 $scope.resourcesType="FUNCTION_POINT";
	}else{
		 $scope.resourcesType=$stateParams.type.toUpperCase();
	}
	var titleMap={"FUNCTION_POINT":"功能点","MENU":"菜单","BUTTON":"按钮"};
   
	$scope.title=titleMap[$scope.resourcesType];
	
	
	function convertData(data){
		var retVal=[];
		for(var i=0;i<data.length;i++){
			retVal.push({"id":data[i],"text":data[i]});
		}
		return retVal;
	}
	
	
	$scope.getRoleList=function(){
		$http.post('api/core/access/role/findAll',{params:{}}).success(function(data, status, headers, config) {
			$scope.roleList=data.data;
		}).error(function(data, status, headers, config) {
	    	alert(data);
        });  
	};
	
	
	var  className = "dark";
	
	function convertToIntegerArray(roleIds){
		var retVal=[];
		for(var i=0;i<roleIds.length;i++){
			retVal.push(parseInt(roleIds[i]));
		}
		return retVal;
	}
	
	function beforeEditName(treeId, treeNode) {
		className = (className === "dark" ? "":"dark");
		var zTree = $.fn.zTree.getZTreeObj("ztree");
		zTree.selectNode(treeNode);
		$scope.editEntity["nameZh"]=treeNode.nameZh;
		$scope.editEntity["nameEn"]=treeNode.nameEn;
		$scope.editEntity["seqNum"]=treeNode.seqNum;
		$scope.editEntity["id"]=treeNode.id;
		$scope.editEntity["url"]=treeNode["url"];
		$scope.editEntity["parentId"]=(treeNode.pId==null?0:treeNode.pId);
		$scope.selectedRoleForEdit=convertToIntegerArray(treeNode.roleIds);//已选中的关联角色
		$scope.$apply();//更新数据
		
		$('#editModal').modal('show');
		return false;//false表示不显示编辑状态
	}
	
	function beforeRemove(treeId, treeNode) {
		className = (className === "dark" ? "":"dark");
		var zTree = $.fn.zTree.getZTreeObj("ztree");
		zTree.selectNode(treeNode);
		if(confirm("确认删除 “" + treeNode.name + "” 吗？")){
			$scope.doDelete(treeNode.id);
		}
		return false;
	}
	
	function onRemove(e, treeId, treeNode) {
		
	}
	function beforeRename(treeId, treeNode, newName, isCancel) {
		className = (className === "dark" ? "":"dark");
		if (newName.length == 0) {
			alert("节点名称不能为空.");
			var zTree = $.fn.zTree.getZTreeObj("ztree");
			setTimeout(function(){zTree.editName(treeNode)}, 10);
			return false;
		}
		return true;
	}
	function onRename(e, treeId, treeNode, isCancel) {
		
	}
	/**
	 * 是否显示删除按钮
	 * @param treeId
	 * @param treeNode
	 * @returns {Boolean}
	 */
	function showRemoveBtn(treeId, treeNode) {
		if(treeNode.id==1){
			return false;
		}
		return true;
	}
	/**
	 * 是否显示编辑按钮
	 * @param treeId
	 * @param treeNode
	 * @returns {Boolean}
	 */
	function showRenameBtn(treeId, treeNode) {
		return true;
	}


	
	function addHoverDom(treeId, treeNode) {
		var sObj = $("#" + treeNode.tId + "_span");
		if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
		
		var addStr = "<span class='button add' id='addBtn_" + treeNode.tId+ "' title='添加' onfocus='this.blur();'></span>";
		sObj.after(addStr);
		var btn = $("#addBtn_"+treeNode.tId);
		if (btn) btn.bind("click", function(){
			$scope.entity["parentId"]=treeNode.id;
			$('#addModal').modal('show');
			return false;
		});
	};
	function removeHoverDom(treeId, treeNode) {
		$("#addBtn_"+treeNode.tId).unbind().remove();
	};
	
	function initTree(treeId,data){
		var setting = {
				view: {
					addHoverDom:addHoverDom,
					removeHoverDom: removeHoverDom,
					selectedMulti: false
				},
				edit: {
					enable: true,
					editNameSelectAll: true,
					showRemoveBtn: showRemoveBtn,
					showRenameBtn: showRenameBtn
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback: {
					beforeEditName: beforeEditName,
					beforeRemove: beforeRemove,
					beforeRename: beforeRename,
					onRemove: onRemove,
					onRename: onRename
				}
			};
		
		$.fn.zTree.init($("#"+treeId),setting,data);
	};
	
	$scope.loadData=function(){
		var submitData={};
		submitData["resourcesType"]=$scope.resourcesType;
		$(".panel-body").block({ message:'正在加载数据，请稍等...',css: { top: '50%' } });
		$http.post('api/core/access/resources/getZtreeJson',{params:submitData}).success(function(data, status, headers, config) {
			initTree("ztree",data.data);
			$(".panel-body").unblock();
		}).error(function(data, status, headers, config) {
			$(".panel-body").unblock();
	    	alert(data);
        });  
	}
	
	$scope.getRoleList();
	
    $scope.selectedRoleForAdd=[]; 
    $scope.selectedRoleForEdit=[];
    
    $scope.entity={};
    $scope.editEntity={};
    $scope.editEntity.roleIds=[];
    
	$scope.loadData();
	
	  
	     var updateSelected = function(selected,action,id,name){ 
		    if(action == 'add' && selected.indexOf(id) == -1){ 
		      selected.push(id); 
		     } 
		    if(action == 'remove' &&selected.indexOf(id)!=-1){ 
		      var idx = selected.indexOf(id); 
		      selected.splice(idx,1); 
		    }
		   } 
		  
		  $scope.updateSelection = function(selected,$event, id){ 
		    var checkbox = $event.target; 
		    var action = (checkbox.checked?'add':'remove'); 
		    updateSelected(selected,action,id,checkbox.name); 
		  } 
		  
		  $scope.isSelected = function(selected,id){ 
		    return selected.indexOf(id)>=0; 
		  } 
		  
		
			  
		
		  
		
			$scope.save=function(){
				  $scope.entity.roleIds=$scope.selectedRoleForAdd.join(',');
				  $scope.entity["type"]=$scope.resourcesType;
				  var requestJson=JSON.stringify($scope.entity); 
				  $(".modal-dialog").block({ message:'正在执行操作，请稍等...',css: { top: '50%' } });
				$http.post('api/core/access/resources/add',{params:{"requestJson":requestJson}}).success(function(data, status, headers, config) {
					modalService.showAlertModal('注意',data.message);
					$(".modal-dialog").unblock();
					if(data.status==1){
						 $scope.loadData(); 
					     $('#addModal').modal('hide');  
					}
				}).error(function(data, status, headers, config) {
					$(".modal-dialog").unblock();
			    	
		       });  
			};
			
			$scope.getRoleIdList=function(){
				var retVal=[];
				for(var i=0;i<$scope.roleList.length;i++){
					retVal.push($scope.roleList[i].id);
				}
				return retVal;
			};
			
		     $scope.update=function(){
		    	  $scope.editEntity.roleIds=$scope.selectedRoleForEdit.join(',');
		    	  $scope.editEntity.deleteRoleIds=$scope.arraySubtract($scope.getRoleIdList(),$scope.selectedRoleForEdit).join(',');
				  $scope.editEntity["type"]=$scope.resourcesType;
				  var requestJson=JSON.stringify($scope.editEntity); 
		    	  $(".modal-dialog").block({ message:'正在执行操作，请稍等...',css: { top: '50%' } });
		 		$http.post('api/core/access/resources/update',{params:{"requestJson":requestJson}}).success(function(data, status, headers, config) {
		 			modalService.showAlertModal('注意',data.message);
		 			$(".modal-dialog").unblock();
		 			if(data.status==1){
		 					$scope.loadData(); 
		 					$('#editModal').modal('hide');  
		 			}
		 		}).error(function(data, status, headers, config) {
		 			$(".modal-dialog").unblock();
		 	    	
		        });
			};
			$scope.doDelete=function(id){
				$(".modal-dialog").block({ message:'正在执行操作，请稍等...',css: { top: '50%' } });
				$http.post('api/core/access/resources/deleteById',{params:{"id":id}}).success(function(data, status, headers, config) {
					modalService.showAlertModal('注意',data.message);
					$(".modal-dialog").unblock();
					if(data.status==1){
						$scope.loadData(); 
					}
				}).error(function(data, status, headers, config) {
					$(".modal-dialog").unblock();
			    	
		       });  
			}
			
			$scope.showAddRootResourceModal=function(){
				 $scope.entity.parentId=0;
				$('#addModal').modal('show');
			}
			
			$scope.arraySubtract=function(arr1,arr2){
				for (var i = arr1.length - 1; i >= 0; i--) {
				    a = arr1[i];
				    for (var j = arr2.length - 1; j >= 0; j--) {
				        b = arr2[j];
				        if (a == b) {
				            arr1.splice(i, 1);
				            arr2.splice(j, 1);
				            break;
				        }
				    }
				}
				return arr1;
			}
			
		  
	
});
